package com.insigma.business.qrcode.job._bff.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.insigma.business.qrcode.common.converter.TrainingVideoProviderConverter;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.template.area.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.util.ResponseUtils;
import com.insigma.business.qrcode.common.util.SessionUtils;
import com.insigma.business.qrcode.common.vo.BaseDeleteRequest;
import com.insigma.business.qrcode.common.vo.BaseResponse;
import com.insigma.business.qrcode.intell.entity.CommonQaInfoDO;
import com.insigma.business.qrcode.job._bff.TrainBFFProvider;
import com.insigma.business.qrcode.job.dto.TrainingVideoDTO;
import com.insigma.business.qrcode.job.dto.request.TrainingVideoInsertRequest;
import com.insigma.business.qrcode.job.dto.request.TrainingVideoSearchRequest;
import com.insigma.business.qrcode.job.dto.request.TrainingVideoUpdateRequest;
import com.insigma.business.qrcode.job.dto.search.TrainingVideoBSearcher;
import com.insigma.business.qrcode.job.entity.TrainingVideoDO;
import com.insigma.business.qrcode.job.service.TrainingVideoService;
import com.insigma.business.qrcode.soldier.request.BaseGetRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class TrainBFFProviderImpl extends BaseProviderImpl implements TrainBFFProvider {

    @Autowired
    private TrainingVideoService trainingVideoService;

    @Override
    public BaseResponse<TrainingVideoDTO> getTrainingVideo(final BaseGetRequest baseGetRequest){

        final BaseResponse<TrainingVideoDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条TrainingVideo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String)baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final TrainingVideoDO trainingVideoDO = trainingVideoService.get((String)baseGetRequest.getId());
                final TrainingVideoDTO remoteObj = TrainingVideoProviderConverter.convertResponseDO2DTO(trainingVideoDO);
                trainingVideoDO.setReadNum(trainingVideoDO.getReadNum() + 1);
                trainingVideoService.update(trainingVideoDO);

//                if(RpcContextUtil.getSessionSoldier() != null){
//                    String userId = RpcContextUtil.getSessionSoldier().getUserId();
//                    String collect = remoteObj.getCollect();
//                    if (Strings.isBlank(collect)) {
//                        remoteObj.setCollected(false);
//                    } else {
//                        String[] split = collect.split(",");
//                        List<String> list = new ArrayList<>(Arrays.asList(split));
//                        if(list.contains(userId)){
//                            remoteObj.setCollected(true);
//                        }else {
//                            remoteObj.setCollected(false);
//                        }
//                    }
//                }

                ResponseUtils.setupSuccessResponse(baseResponse,remoteObj);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.TRAINING_VIDEO_GET;
            }
        });
        return baseResponse;
    }

    @Override
    public BasePagingResponse<List<TrainingVideoDTO>> searchTrainingVideo(TrainingVideoSearchRequest searchRequest) {

        final BasePagingResponse<List<TrainingVideoDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页TrainingVideo的请求参数不能为空");
            }

            @Override
            public void executeService() {
                final TrainingVideoBSearcher trainingVideoBSearcher = TrainingVideoProviderConverter.convertRequestSO2Searcher(searchRequest);
                PageHelper.startPage(searchRequest.getPageNo(), searchRequest.getPageSize());
                final List<TrainingVideoDO> trainingVideoDOList = trainingVideoService.search(trainingVideoBSearcher);
                PageInfo<TrainingVideoDO> pageinfo = new PageInfo<>(trainingVideoDOList);
                final List<TrainingVideoDTO> trainingVideoDTOList = TrainingVideoProviderConverter.convertResponseDOList2DTOList(trainingVideoDOList);
                ResponseUtils.buildSuccessPagingResponse(basePagingResponse, trainingVideoDTOList, searchRequest,pageinfo.getTotal());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.TRAINING_VIDEO_SEARCH;
            }
        });

        return basePagingResponse;
    }


    @Override
    public BaseResponse<String> insertTrainingVideo(final TrainingVideoInsertRequest insertRequest){

        if(insertRequest.getPublished() == null){
            insertRequest.setPublished(false);
        }
        final BaseResponse<String> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(insertRequest, "新增TrainingVideo的请求参数不能为空");
            }
            @Override
            public void executeService() {
                final TrainingVideoDO trainingVideoDO = TrainingVideoProviderConverter.convertRequestIO2DO(insertRequest);
                if(Objects.isNull(trainingVideoDO.getTop())){
                    trainingVideoDO.setTop(Boolean.FALSE);
                }
                if(trainingVideoDO.getTop()){
                    trainingVideoDO.setTopWeight(getTrainingVideoMaxTopWeight());
                }else {
                    trainingVideoDO.setTopWeight(0);
                }

                List<Object> list = JSONObject.parseArray(trainingVideoDO.getCatalog());
                trainingVideoDO.setCatalogNum(list.size());
                trainingVideoDO.setReadNum(0);
                trainingVideoDO.setILike(0);
                trainingVideoDO.setDislike(0);
                trainingVideoService.insert(trainingVideoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, trainingVideoDO.getId());
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.TRAINING_VIDEO_INSERT;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> updateTrainingVideo(final TrainingVideoUpdateRequest updateRequest){

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改TrainingVideo的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
                //BizCheckUtil.checkNotBlank(updateRequest.getModifierId(),"操作人不能为空");
               // BizCheckUtil.checkNotBlank(updateRequest.getModifierType(),"操作人类型不能为空");
               //BizCheckUtil.checkNotBlank(updateRequest.getCatalog(), "章节不能为空");
            }
            @Override
            public void executeService() {
                SessionUtils.buildModifierOfGov(updateRequest);
                TrainingVideoDO TrainingVideoCurrentDO = trainingVideoService.get(updateRequest.getId());
                TrainingVideoDO trainingVideoDO = TrainingVideoProviderConverter.convertRequestUO2DO(updateRequest);

                List<Object> list = JSONObject.parseArray(trainingVideoDO.getCatalog());
                trainingVideoDO.setCatalogNum(list.size());



                if(Objects.isNull(trainingVideoDO.getTop())){
                    trainingVideoDO.setTop(Boolean.FALSE);
                }

                if (Boolean.TRUE.equals(trainingVideoDO.getTop())) {
                    trainingVideoDO.setTopWeight(TrainingVideoCurrentDO.getTopWeight());
                } else {
                    trainingVideoDO.setTopWeight(0);
                }
                trainingVideoDO.setCollect(TrainingVideoCurrentDO.getCollect());
                Integer affectRowNum = trainingVideoService.update(trainingVideoDO);
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.TRAINING_VIDEO_UPDATE;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> publishTrainingVideo(TrainingVideoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "修改TrainingVideo的请求参数不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
       // BizCheckUtil.checkNotBlank(updateRequest.getModifierId(),"操作人不能为空");
       // BizCheckUtil.checkNotBlank(updateRequest.getModifierType(),"操作人类型不能为空");
        String[] ids = updateRequest.getId().split(",");
        int updates = 0;
        for(String id : ids){
            updateRequest.setId(id);
            SessionUtils.buildModifierOfGov(updateRequest);
            TrainingVideoDO trainingVideoDO = trainingVideoService.get(updateRequest.getId());
            BizCheckUtil.checkNotNull(trainingVideoDO, "数据不存在");

            trainingVideoDO.setPublished(updateRequest.getPublished());
            trainingVideoDO.setModifierId(updateRequest.getModifierId());
            trainingVideoDO.setModifierType(updateRequest.getModifierType());
            trainingVideoDO.setModifyDatetime(updateRequest.getModifyDatetime());
            Integer update = trainingVideoService.update(trainingVideoDO);
            updates += update;
        }

        return ResponseUtils.buildSuccessResponse(updates);
    }


    @Override
    public BaseResponse<Integer> topTrainingVideo(TrainingVideoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "置顶TrainingVideo的请求参数不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
        //BizCheckUtil.checkNotBlank(updateRequest.getModifierId(),"操作人不能为空");
        //BizCheckUtil.checkNotBlank(updateRequest.getModifierType(),"操作人类型不能为空");
        SessionUtils.buildModifierOfGov(updateRequest);
        TrainingVideoDO trainingVideoDO = trainingVideoService.get(updateRequest.getId());
        BizCheckUtil.checkNotNull(trainingVideoDO, "数据不存在");

        if(updateRequest.getTop()){
            trainingVideoDO.setTopWeight(getTrainingVideoMaxTopWeight());
        }else {
            trainingVideoDO.setTopWeight(0);
        }

        trainingVideoDO.setTop(updateRequest.getTop());
        trainingVideoDO.setModifierId(updateRequest.getModifierId());
        trainingVideoDO.setModifierType(updateRequest.getModifierType());
        trainingVideoDO.setModifyDatetime(updateRequest.getModifyDatetime());
        Integer update = trainingVideoService.update(trainingVideoDO);

        return ResponseUtils.buildSuccessResponse(update);
    }

    @Override
    public BaseResponse<Integer> collectTrainingVideo(TrainingVideoUpdateRequest updateRequest) {

        BizCheckUtil.checkNotNull(updateRequest, "收藏TrainingVideo的请求参数不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getModifierId(),"操作人不能为空");
        BizCheckUtil.checkNotBlank(updateRequest.getModifierType(),"操作人类型不能为空");

        TrainingVideoDO trainingVideoDO = trainingVideoService.get(updateRequest.getId());
        BizCheckUtil.checkNotNull(trainingVideoDO, "数据不存在");

        String[] split = new String[0];
        if(!StringUtils.isBlank(trainingVideoDO.getCollect())){
            split = trainingVideoDO.getCollect().split(",");
        }
        Set<String> hashSet = new HashSet<>(Arrays.asList(split));
        if(updateRequest.getCollected()){
            hashSet.add(updateRequest.getModifierId());
        }else{
            hashSet.remove(updateRequest.getModifierId());
        }
        trainingVideoDO.setCollect(StringUtils.join(hashSet,","));
        trainingVideoDO.setModifierId(updateRequest.getModifierId());
        trainingVideoDO.setModifierType(updateRequest.getModifierType());
        trainingVideoDO.setModifyDatetime(updateRequest.getModifyDatetime());
        Integer update = trainingVideoService.update(trainingVideoDO);

        return ResponseUtils.buildSuccessResponse(update);
    }

    private Integer getTrainingVideoMaxTopWeight() {
        Integer maxTopWeight = trainingVideoService.getTrainingVideoMaxTopWeight();
        if(maxTopWeight == null){
            maxTopWeight = 1;
        }else {
            maxTopWeight += 1;
        }

        return maxTopWeight;
    }


    @Override
    public BaseResponse<Integer> deleteTrainingVideo(final BaseDeleteRequest deleteRequest){

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除TrainingVideo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String)deleteRequest.getId(), "id不能为空");
                //BizCheckUtil.checkNotBlank(deleteRequest.getModifierType(),"操作人类型不能为空");
                //BizCheckUtil.checkNotBlank((String)deleteRequest.getModifierId(),"操作人不能为空");
            }
            @Override
            public void executeService() {
                SessionUtils.buildDeleteOfGov(deleteRequest);
                final Integer affectRowNum = trainingVideoService.delete((String)deleteRequest.getId(),deleteRequest.getModifierType(),(String)deleteRequest.getModifierId());
                ResponseUtils.setupSuccessResponse(baseResponse, affectRowNum);
            }
            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.TRAINING_VIDEO_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }

}
